
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSpinner.DefaultEditor;
import javax.swing.Timer;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * FrmMain.java
 *
 * Created on May 27, 2011, 2:37:23 PM
 */

/**
 *
 * @author ei08109
 */
public class FrmMain extends javax.swing.JFrame implements ActionListener {

	static private final int TAB_GERAL_INDEX = 0;
	static private final int TAB_DETALHE_INDEX = 1;

	static private final int REFRESH_INTERVAL = 1000 * 10;
	static private final int NUMBER_OF_QUEUES_PER_LINE = 3;

	private Timer timerRefresh;
	private int selectedService = -1;

	JLabel[] lblGeralLetra;
	JLabel[] lblGeralNum;
	JLabel[] lblGeralBalcao;
	JLabel[] imgAlerta;
	JPanel[] painelGeral;

    /** Creates new form FrmMain */
    public FrmMain() {
		initComponents();
		((DefaultEditor)spnAlertasNumSenhas.getEditor()).getTextField().setEditable(false);

		initInfo();

		pack();

		pnlTab.setEnabledAt(TAB_DETALHE_INDEX, false);
		timerRefresh = new Timer(REFRESH_INTERVAL, this);
		timerRefresh.start();

		refreshInfos();
    }

	private void initInfo() {
		final int size = Client.getQueues().length;
		lblGeralLetra = new JLabel[size];
		lblGeralNum = new JLabel[size];
		lblGeralBalcao = new JLabel[size];
		imgAlerta = new JLabel[size];
		painelGeral = new JPanel[size];

		pnlGeral.setLayout(new java.awt.GridLayout((size + NUMBER_OF_QUEUES_PER_LINE - 1) / NUMBER_OF_QUEUES_PER_LINE, 1));

		int i = 0;
		JPanel painel = null;
		for(QueueInformation q: Client.getQueues()) {
			// Criar um painel de N em N filas
			if(i % NUMBER_OF_QUEUES_PER_LINE == 0) {
				painel = new JPanel();
				painel.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER, 20, 5));
				pnlGeral.add(painel);
			}
			final int id = q.getId();
			String code = "" + q.getCode();

			// Criar e preencher o painel da fila
			painelGeral[id] = new JPanel();
			painel.add(painelGeral[id]);
			painelGeral[id].setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
			painelGeral[id].setPreferredSize(new java.awt.Dimension(110, 100));
			painelGeral[id].addMouseListener(new java.awt.event.MouseAdapter() {
				@Override
				public void mouseClicked(java.awt.event.MouseEvent evt) {
					selectService(id);
				}
			});
			painelGeral[id].setLayout(new java.awt.GridLayout(2, 2, 10, 0));

			lblGeralLetra[id] = new JLabel();
			lblGeralLetra[id].setFont(new java.awt.Font("DejaVu Sans", 1, 36));
			lblGeralLetra[id].setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
			lblGeralLetra[id].setText(code);
			lblGeralLetra[id].addMouseListener(new java.awt.event.MouseAdapter() {
				@Override
				public void mouseClicked(java.awt.event.MouseEvent evt) {
					selectService(id);
				}
			});
			painelGeral[id].add(lblGeralLetra[id]);

			lblGeralNum[id] = new JLabel();
			lblGeralNum[id].setFont(new java.awt.Font("DejaVu Sans", 0, 24));
			lblGeralNum[id].setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
			lblGeralNum[id].setToolTipText("Última senha");
			lblGeralNum[id].addMouseListener(new java.awt.event.MouseAdapter() {
				@Override
				public void mouseClicked(java.awt.event.MouseEvent evt) {
					selectService(id);
				}
			});
			painelGeral[id].add(lblGeralNum[id]);

			lblGeralBalcao[id] = new JLabel();
			lblGeralBalcao[id].setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
			lblGeralBalcao[id].setToolTipText("Balcão");
			lblGeralBalcao[id].addMouseListener(new java.awt.event.MouseAdapter() {
				@Override
				public void mouseClicked(java.awt.event.MouseEvent evt) {
					selectService(id);
				}
			});
			painelGeral[id].add(lblGeralBalcao[id]);

			imgAlerta[id] = new JLabel();
			imgAlerta[id].setHorizontalAlignment(JLabel.RIGHT);
			imgAlerta[id].setVerticalAlignment(JLabel.BOTTOM);
			painelGeral[id].add(imgAlerta[id]);

			i++;
		}
	}

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnlTab = new javax.swing.JTabbedPane();
        pnlGeral = new javax.swing.JPanel();
        pnlDetalhe = new javax.swing.JPanel();
        lblDetalheLetra = new javax.swing.JLabel();
        lblDetalheNum = new javax.swing.JLabel();
        lblDetalheB = new javax.swing.JLabel();
        lblDetalheBalcao = new javax.swing.JLabel();
        lblDetalheNome = new javax.swing.JLabel();
        lblHoraAtendimento = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        lblNumeroTotal = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jLabel4 = new javax.swing.JLabel();
        lblHoraPrevistaImpressa = new javax.swing.JLabel();
        lblUltimaSenhaImpressa = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        lblHoraImpressao = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jLabel6 = new javax.swing.JLabel();
        txtNumeroMinhaSenha = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        spnAlertasNumSenhas = new javax.swing.JSpinner();
        jLabel8 = new javax.swing.JLabel();
        chkActivarAlerta = new javax.swing.JCheckBox();
        jMenuBar1 = new javax.swing.JMenuBar();
        mnuFile = new javax.swing.JMenu();
        mnuRefresh = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JPopupMenu.Separator();
        mnuExit = new javax.swing.JMenuItem();
        mnuHelp = new javax.swing.JMenu();
        mnuAbout = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle(Client.NAME);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        pnlTab.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                pnlTabStateChanged(evt);
            }
        });

        pnlGeral.setLayout(new java.awt.GridLayout(2, 1));
        pnlTab.addTab("Geral", pnlGeral);

        lblDetalheLetra.setFont(new java.awt.Font("DejaVu Sans", 1, 48)); // NOI18N
        lblDetalheLetra.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblDetalheLetra.setText("A");

        lblDetalheNum.setFont(new java.awt.Font("DejaVu Sans", 0, 48)); // NOI18N
        lblDetalheNum.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblDetalheNum.setText("0");
        lblDetalheNum.setToolTipText("Última senha");

        lblDetalheB.setFont(new java.awt.Font("DejaVu Sans", 1, 24)); // NOI18N
        lblDetalheB.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);

        lblDetalheBalcao.setFont(new java.awt.Font("DejaVu Sans", 0, 24)); // NOI18N
        lblDetalheBalcao.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lblDetalheBalcao.setText("Balcão:");

        lblDetalheNome.setFont(new java.awt.Font("DejaVu Sans", 0, 24)); // NOI18N
        lblDetalheNome.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblDetalheNome.setText("Serviço");

        jLabel3.setText("Atendida às");

        jLabel5.setText("Número total de pessoas à espera em todos os serviços:");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Última senha impressa", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Dialog", 0, 15))); // NOI18N

        jLabel4.setText("Hora prevista de atendimento:");

        lblUltimaSenhaImpressa.setFont(new java.awt.Font("Ubuntu", 0, 24)); // NOI18N
        lblUltimaSenhaImpressa.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);

        jLabel2.setText("Hora de impressão:");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblUltimaSenhaImpressa, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel4)
                    .addComponent(jLabel2))
                .addGap(20, 20, 20)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(lblHoraPrevistaImpressa, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(lblHoraImpressao, javax.swing.GroupLayout.DEFAULT_SIZE, 111, Short.MAX_VALUE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblHoraImpressao, javax.swing.GroupLayout.DEFAULT_SIZE, 18, Short.MAX_VALUE)
                            .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 12, Short.MAX_VALUE)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblHoraPrevistaImpressa, javax.swing.GroupLayout.DEFAULT_SIZE, 18, Short.MAX_VALUE)
                            .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.TRAILING))
                        .addGap(15, 15, 15))
                    .addComponent(lblUltimaSenhaImpressa, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Minha senha", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Dialog", 0, 15))); // NOI18N

        jLabel6.setFont(new java.awt.Font("Ubuntu", 0, 18)); // NOI18N
        jLabel6.setText("Número:");

        jLabel7.setText("Avisar quando faltarem");

        spnAlertasNumSenhas.setModel(new javax.swing.SpinnerNumberModel(5, 0, 20, 1));

        jLabel8.setText("senhas.");

        chkActivarAlerta.setText("Activar alerta");
        chkActivarAlerta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chkActivarAlertaActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(52, 52, 52)
                        .addComponent(jLabel6)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtNumeroMinhaSenha, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel7)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(spnAlertasNumSenhas, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel8)))
                .addContainerGap(34, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap(79, Short.MAX_VALUE)
                .addComponent(chkActivarAlerta)
                .addGap(77, 77, 77))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel6)
                    .addComponent(txtNumeroMinhaSenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(spnAlertasNumSenhas, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel8)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(chkActivarAlerta)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout pnlDetalheLayout = new javax.swing.GroupLayout(pnlDetalhe);
        pnlDetalhe.setLayout(pnlDetalheLayout);
        pnlDetalheLayout.setHorizontalGroup(
            pnlDetalheLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlDetalheLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlDetalheLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblDetalheNome, javax.swing.GroupLayout.DEFAULT_SIZE, 454, Short.MAX_VALUE)
                    .addGroup(pnlDetalheLayout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblNumeroTotal, javax.swing.GroupLayout.DEFAULT_SIZE, 54, Short.MAX_VALUE))
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(pnlDetalheLayout.createSequentialGroup()
                        .addGroup(pnlDetalheLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(pnlDetalheLayout.createSequentialGroup()
                                .addGap(8, 8, 8)
                                .addComponent(lblDetalheLetra, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(lblDetalheNum, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(pnlDetalheLayout.createSequentialGroup()
                                .addGroup(pnlDetalheLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(lblDetalheBalcao, javax.swing.GroupLayout.Alignment.LEADING))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(pnlDetalheLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(lblDetalheB, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(lblHoraAtendimento, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap())
        );
        pnlDetalheLayout.setVerticalGroup(
            pnlDetalheLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlDetalheLayout.createSequentialGroup()
                .addComponent(lblDetalheNome)
                .addGroup(pnlDetalheLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(pnlDetalheLayout.createSequentialGroup()
                        .addGap(9, 9, 9)
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(pnlDetalheLayout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addGroup(pnlDetalheLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblDetalheNum, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblDetalheLetra, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(pnlDetalheLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(lblHoraAtendimento, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel3))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(pnlDetalheLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(lblDetalheB, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(lblDetalheBalcao))))
                .addGap(39, 39, 39)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnlDetalheLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel5)
                    .addComponent(lblNumeroTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        pnlTab.addTab("Serviço", pnlDetalhe);

        getContentPane().add(pnlTab, java.awt.BorderLayout.CENTER);

        mnuFile.setMnemonic(KeyEvent.VK_F);
        mnuFile.setText("Ficheiro");

        mnuRefresh.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F5, 0));
        mnuRefresh.setMnemonic(KeyEvent.VK_A);
        mnuRefresh.setText("Actualizar");
        mnuRefresh.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuRefreshActionPerformed(evt);
            }
        });
        mnuFile.add(mnuRefresh);
        mnuFile.add(jSeparator1);

        mnuExit.setMnemonic(KeyEvent.VK_S);
        mnuExit.setText("Sair");
        mnuExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuExitActionPerformed(evt);
            }
        });
        mnuFile.add(mnuExit);

        jMenuBar1.add(mnuFile);

        mnuHelp.setMnemonic(KeyEvent.VK_A);
        mnuHelp.setText("Ajuda");

        mnuAbout.setMnemonic(KeyEvent.VK_A);
        mnuAbout.setText("Acerca");
        mnuAbout.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuAboutActionPerformed(evt);
            }
        });
        mnuHelp.add(mnuAbout);

        jMenuBar1.add(mnuHelp);

        setJMenuBar(jMenuBar1);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void mnuExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuExitActionPerformed
		exit();
    }//GEN-LAST:event_mnuExitActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
		exit();
    }//GEN-LAST:event_formWindowClosing

    private void mnuAboutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuAboutActionPerformed
		JOptionPane.showMessageDialog(null, "Acerca do " + Client.NAME + "...\n\nFeito pelos alunos da FEUP:\n-Bruno Nova\n-Francisca Teixeira\n-Ricardo Cunha\n-Rolando Pereira", Client.NAME, JOptionPane.INFORMATION_MESSAGE);
    }//GEN-LAST:event_mnuAboutActionPerformed

    private void pnlTabStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_pnlTabStateChanged
		if(pnlTab.getSelectedIndex() == TAB_DETALHE_INDEX) {
			updateSelectedInfoText();
		}
    }//GEN-LAST:event_pnlTabStateChanged

	private void chkActivarAlertaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkActivarAlertaActionPerformed
		if(chkActivarAlerta.isSelected())
			enableAlert(selectedService);
		else
			disableAlert(selectedService);
}//GEN-LAST:event_chkActivarAlertaActionPerformed

	private void enableAlert(int id) {
		int number = Integer.parseInt(txtNumeroMinhaSenha.getText());
		Integer numTickets = (Integer)spnAlertasNumSenhas.getValue();

		if(id == selectedService) {
			txtNumeroMinhaSenha.setEnabled(false);
			spnAlertasNumSenhas.setEnabled(false);
			chkActivarAlerta.setSelected(true);
		}
		imgAlerta[id].setIcon(new javax.swing.ImageIcon("images/bell.png"));
		imgAlerta[id].setToolTipText("Alerta activado. Número: " + number);

		Client.getAlert(id).activateAlert(number, numTickets);
	}

	private void disableAlert(int id) {
		if(id == selectedService) {
			txtNumeroMinhaSenha.setEnabled(true);
			spnAlertasNumSenhas.setEnabled(true);
			chkActivarAlerta.setSelected(false);
		}
		imgAlerta[id].setIcon(null);
		imgAlerta[id].setToolTipText(null);

		Client.getAlert(id).disable();
	}

	private void mnuRefreshActionPerformed(java.awt.event.ActionEvent evt) {                                           
		refreshInfos();
		
		timerRefresh.stop();
		timerRefresh.setDelay(REFRESH_INTERVAL);
		timerRefresh.start();
		
	}

	private void refreshInfos() {
		try {
			Client.getInfoForAllQueues(); //volta a buscar todas as filas e suas informacoes da BD
			
			updateInfosText();
			updateSelectedInfoText();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void updateInfosText() {
		for(QueueInformation q: Client.getQueues()) {
			int id = q.getId();
			lblGeralBalcao[id].setText(q.getDesk());
			lblGeralNum[id].setText(q.getCurrentTicket());

			checkAlert(q);
		}
	}

	private QueueInformation updateSelectedInfoText() {
		if(selectedService == -1)
			return null;

		QueueInformation q = null;
		try {
			q = Client.getInfobyServiceId(selectedService);
        } catch (IOException ex) {
			Logger.getLogger(FrmMain.class.getName()).log(Level.SEVERE, null, ex);
			return null;
        }

		lblDetalheB.setText(q.getDesk());
		lblDetalheNum.setText(q.getCurrentTicket());
		lblHoraAtendimento.setText(q.getTicketServedHour());
		lblUltimaSenhaImpressa.setText(q.getLastTicketPrintedNumber());
		lblHoraImpressao.setText(q.getLastTicketPrintedHour());
		lblHoraPrevistaImpressa.setText(q.getExpectedTimeToBeServed());
		lblNumeroTotal.setText(q.getAllRemainingTickets());

		checkAlert(q);
		return q;
	}

	private void checkAlert(QueueInformation q) {
		int id = q.getId();
		QueueAlert alert = Client.getAlert(id);
		if(!alert.isEnabled())
			return;
		int userNumber = alert.getTicketNumber();
		int queueNumber;
		try {
			queueNumber = Integer.parseInt(q.getCurrentTicket());
		}
		catch(NumberFormatException e) {
			return;
		}
		int numberOfTickets = alert.getNumberOfTicketsBeforeAlert();

		if(userNumber <= (queueNumber + numberOfTickets)) { // Está na "hora" de dar o alerta?
			disableAlert(id);
			String msg = null;
			if(userNumber > queueNumber)
				msg = "Alerta!\nEstá a chegar a sua vez no serviço " + q.getCode() + ".";
			else if(userNumber == queueNumber)
				msg = "Alerta!\nChegou a sua vez no serviço " + q.getCode() + "!\nDirija-se ao balcão " + q.getDesk() + ".";
			else
				msg = "Alerta!\nJá passou a sua vez no serviço " + q.getCode() + "!\nDirija-se o mais rapidamente possível ao balcão!";
			JOptionPane.showMessageDialog(null, msg, Client.NAME, JOptionPane.WARNING_MESSAGE);
		}
	}

    private void selectService(int service) {
		selectedService = service;

		char code = Client.getQueue(service).getCode();
		String name = Client.getQueue(service).getDescription();

		updateSelectedInfoText();

		lblDetalheLetra.setText("" + code);
		lblDetalheNome.setText(name);

		QueueAlert alert = Client.getAlert(selectedService);
		txtNumeroMinhaSenha.setText("" + alert.getTicketNumber());
		spnAlertasNumSenhas.setValue(alert.getNumberOfTicketsBeforeAlert());
		chkActivarAlerta.setSelected(alert.isEnabled());
		if(alert.isEnabled()) {
			txtNumeroMinhaSenha.setEnabled(false);
			spnAlertasNumSenhas.setEnabled(false);
		}
		else {
			txtNumeroMinhaSenha.setEnabled(true);
			spnAlertasNumSenhas.setEnabled(true);
		}

		pnlTab.setSelectedIndex(TAB_DETALHE_INDEX);
		pnlTab.setTitleAt(TAB_DETALHE_INDEX, "Serviço " + code);
		pnlTab.setEnabledAt(TAB_DETALHE_INDEX, true);
    }

    private void exit() {
		if(JOptionPane.showConfirmDialog(null, "Tem a certeza que quer sair?", Client.NAME, JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION)
			System.exit(0);
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JCheckBox chkActivarAlerta;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPopupMenu.Separator jSeparator1;
    private javax.swing.JLabel lblDetalheB;
    private javax.swing.JLabel lblDetalheBalcao;
    private javax.swing.JLabel lblDetalheLetra;
    private javax.swing.JLabel lblDetalheNome;
    private javax.swing.JLabel lblDetalheNum;
    private javax.swing.JLabel lblHoraAtendimento;
    private javax.swing.JLabel lblHoraImpressao;
    private javax.swing.JLabel lblHoraPrevistaImpressa;
    private javax.swing.JLabel lblNumeroTotal;
    private javax.swing.JLabel lblUltimaSenhaImpressa;
    private javax.swing.JMenuItem mnuAbout;
    private javax.swing.JMenuItem mnuExit;
    private javax.swing.JMenu mnuFile;
    private javax.swing.JMenu mnuHelp;
    private javax.swing.JMenuItem mnuRefresh;
    private javax.swing.JPanel pnlDetalhe;
    private javax.swing.JPanel pnlGeral;
    private javax.swing.JTabbedPane pnlTab;
    private javax.swing.JSpinner spnAlertasNumSenhas;
    private javax.swing.JTextField txtNumeroMinhaSenha;
    // End of variables declaration//GEN-END:variables

	// Action Listener do timer
    public void actionPerformed(ActionEvent e) {
		if(e.getSource() == timerRefresh) {
			refreshInfos();
			timerRefresh.setDelay(REFRESH_INTERVAL);
			timerRefresh.start();
		}
    }

}
